<template>
  <view class="confirm-order-wrap" v-if="!loading"  >
    <!--  地址  -->
    <view
    @tap="handleToAddress"
    class="address"
    :style="'background: url(' + addressBg + ') no-repeat left bottom;'">
      <view class="address__section" >
        <view class="address__content">
          <template v-if="address">
            <view class="address__user">
              <text class="address__user-name">{{ address.delivery_name }}</text>
              <text class="address__user-mobile">{{ address.mobile }}</text>
            </view>
            <view class="address__info">
              {{ address.region }}{{ address.address }}
            </view>
          </template>
          <view class="address__empty" v-else>请选择收货地址</view>
        </view>
      </view>
      <view class="address__action iconfont icon-arrow-right"></view>
    </view>

    <!-- 商品信息 -->
    <view class="bill" v-for="(goodInfo) in goodInfos" :key="goodInfo.itemId">
      <view class="item-card-wrap">
        <image
          class="pic"
          :src="goodInfo.url?goodInfo.url:goodInfo.thumbs[0]"
        ></image>
        <view class="info">
          <view class="info__title">{{ goodInfo.item_name }}</view>
          <view class="info__sale">
            <text>¥{{ goodInfo && goodInfo.price | changeSub }}</text>
          </view>
          <view>数量：{{goodInfo.cnt}}</view>
        </view>
      </view>
    </view>
    <view class="agree" @tap="agree = !agree" >
        <view :class="['iconfont icon-circle', agree ? 'icon-xuanzhong on' : 'icon-xuanzhongyuandian']" ></view>
        <view style="color: #999999;" >同意<text style="color: #007AFF;" @tap.stop="handleToXieyi" >《用户协议》</text></view>
      </view>
    <view class="tip-box" >
      <view class="tip" >注：当前订购只显示为线上预定，需线下进行支付</view>
    </view>

    <!-- 操作 -->
    <view class="btn-box">
      <view  v-if="paytype===0" class="total-price"><text class="price">合计：¥0</text></view>
      <!-- <view v-else class="total-price">合计：<text class="price">¥{{ (totalFee / 100).toFixed(2) }}</text></view> -->
      <view v-else class="total-price">
        <text class="price">¥{{ (totalFee / 100 - (selectedCoupon ? selectedCoupon.amount : 0)).toFixed(2) }}</text>
      </view>
      <picker
        v-if="coupons.length>0"
        mode="selector"
        :range="coupons"
        range-key="name"
        :value="selectedCouponIndex"
        @change="handleCouponChange"
      >
        <view class="coupon-picker">
          {{ selectedCoupon ? `${selectedCoupon.name}(¥${selectedCoupon.amount})` : '选择优惠券' }}
        </view>
      </picker>

      <button
      @tap="handleToCreate"
      :class="['pp-button pay-btn', '']"
       hover-class="pp-button--active">
        提交订单
      </button>
    </view>
  </view>
</template>

<script>
import { addressBg } from '@/tool/static-img';
import { RECEIVER_LIST, RECEIVER_INFO } from '@/api/user';
import { ORDER_CREATE, PAY_SIGN } from '@/api/order';
import { GOOD_DETAIL } from '@/api/good';
import Stepper from '@/basic-components/u-stepper/index.vue';
import { COUPON_MY } from '@/api/coupon';

export default {
  components: {
    Stepper,
  },
  data() {
    return {
      addressBg,
      num: 1,
      agree: false,
      address: null,
      goodInfos: [],
      loading: true,
      shopId:'',
      paytype:0,
      coupons: [],
      shoppingCarId:'',
      selectedCoupon: null,
      selectedCouponIndex: -1, // 选中的优惠券索
    };
  },
  computed: {
    //disable() {

      //return !(this.agree && this.address);
    //},
    totalPrice() {
      if(!this.goodInfo) {
        return ''
      }

      return this.num * this.goodInfo.price
    }
  },
  async onLoad(option) {
    uni.hideShareMenu();
    
    const { goodInfos, address, goodId, addressId, totalFee,shopId ,shoppingCarId} = option;
    this.shopId=shopId;
    this.shoppingCarId=shoppingCarId;
    await this.fetchCoupons();
    // 再下一单
    if(goodId && addressId) {
      this.getGoodInfo(goodId);
      this.getAddressDetail(addressId)
    }else {
      // 无地址时获取默认地址
      if (!this.address) {
        await this.getDefaultAddress();
      }

      this.goodInfos = JSON.parse(decodeURIComponent(goodInfos));
      
      for (let i = 0; i < this.goodInfos.length; i++) {
          if( this.goodInfos[i].online_pay===1){
            this.paytype=1;
            break ;
        }
      }
      
    } 
    this.totalFee = totalFee;

    this.loading = false;
    
  },
  onShow(option) {
    // 地址选择
    if (option && option.type === 'address') {
      this.address = option.params;
    }
    if(option && option.type === 'shippingCart'){
      this.goodInfos = JSON.parse(decodeURIComponent(option.goodInfos));
    }
  },
  methods: {
    handleToXieyi() { //
      this.$navigate({
        page: 'xieyi',
      });
    },
    async getDefaultAddress() {
      const regionId = uni.getStorageSync('regionId');
      // 默认地址
      const { data } = await this.$http.get(RECEIVER_LIST, {
        is_default: 1,
        village:'C'+regionId
      });
      if (data && data.length) {
        this.address = data[0];
      }
    },
    async fetchCoupons() {
    const params = {
      // 根据需要添加参数
      type:1,
      sttus: 1,
      shop_id: this.shopId
    };
    try {
      const response = await this.$http.get(COUPON_MY, params);
      this.coupons = response.data.map(coupon => ({
        id: coupon.id,
        name: coupon.coupon.name,
        shop_name: coupon.coupon.issue_merchant,
        amount: coupon.coupon.offer_amount,
      }))
      .filter(coupon => (this.totalFee / 100 - coupon.amount) >= 0);
    } catch (error) {
      console.error('获取优惠券失败', error);
    }
  },
   // ... 其他方法
   handleCouponChange(event) {
  const index = event.detail.value;
  const selectedCoupon = this.coupons[index];
  if (selectedCoupon && (this.totalFee / 100 - selectedCoupon.amount) < 0) {
    uni.showToast({
      title: '优惠券金额过大，无法使用',
      icon: 'none',
    });
    this.selectedCouponIndex = -1;
    this.selectedCoupon = null;
  } else {
    this.selectedCouponIndex = index;
    this.selectedCoupon = selectedCoupon;
  }
},
    getGoodInfo(id) {
      this.$http.get(`${GOOD_DETAIL}/${id}`)
        .then(res => {
          let data = res.data;
          data.thumbs = data.thumbs.split(',');
          this.goodInfo = data;
        })
    },
    getAddressDetail(id) {
      this.$http.get(RECEIVER_INFO +'/' + id)
        .then(res => {
          this.address = res.data;
        })
    },
    handleToChangeNum(data) {
      this.num = data;
    },
    handleToAddress() {
      // 去地址接口
      this.$navigate({
        page: 'address',
      });
    },
    handleToCreate() {
      if(!this.address){
        uni.showToast({
          title: '请先选择地址',
          icon: 'none',
        });
        return
      }
      if(!this.agree){
        uni.showToast({
          title: '请同意用户协议',
          icon: 'none',
        });
        return
      }
      if(this.disable) {
        return
      }
      // let itemIds=[];
      const itemList = this.goodInfos.map((item)=> {
        return {
          itemId: item?.id,
          cnt: item?.cnt  
        }
      })
      const params = {
        shop_id: this.shopId,
        delivery_id: this.address.id,
        region_id: uni.getStorageSync('regionId'),
        pay_type: this.paytype===0?1:2,
        order_type:1,
        item_list: itemList, 
        agree:this.agree,     
        coupon_id: this.selectedCoupon ? this.selectedCoupon.id : null, // 添加优惠券ID
      };
      // params['delivery_id'] = this.address.id ;
      // params['item_list'] = this.goodInfos;
      // params['amount'] = this.num || 1;
      // params['shop_id']=this.shopId;
      // params['shop_car_id']=this.shoppingCarId;
      // params['pay_type']=2;
      // params['oneline_pay']=2;
      // params['region_id']=uni.getStorageSync('regionId');
      
      // this.goodInfos.forEach(item=>{
      //   itemIds.push(item.id);
      // });

      this.$http.post(ORDER_CREATE, params, {
        showLoading: true
      })
      .then((res) => {
        uni.setStorageSync('agree', 1);
        uni.hideLoading();
        uni.setStorageSync(this.shopId+'shopCar', 0);
        //this.clearShoppingCar();
        // 线下支付
        if(this.paytype === 0) {
          setTimeout(() => {
            uni.showToast({
              icon: 'success',
              mask: true,
              title: '提交成功',
              duration: 1200,
            });
          }, 300)
          
          setTimeout(() => {
            this.$navigate({
              page: 'order'
            })
          }, 1500);
        }else if(this.paytype === 1) {
          // 线上支付
          this.getPayment(res.data.id)
        }
      })
    },
    getPaymentSign(sn) {
      // PAY_SIGN
      return this.$http.put(PAY_SIGN, {
        id: sn
      })
    },
    async getPayment(sn) {
      uni.showToast({
        title: '请求中...',
        mask: true,
        icon: 'loading',
        duration: 300000,
      });
      try{
        const entry = await this.getPaymentSign(sn);
        const {
          data
        } = entry;
        uni.requestPayment({
          timeStamp: data.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
          nonceStr: data.nonceStr, // 支付签名随机串，不长于 32 位
          package: data.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
          signType: data.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
          paySign: data.paySign,
          success: res => {
            setTimeout(() => {
              this.$navigate({
                page: 'order'
              })
            }, 300)
            
            uni.hideToast();
            if (res.errMsg === 'requestPayment:ok') {
              uni.showToast({
                title: '创建成功',
                icon: 'success',
              });
            } 
          },
          fail: () => {
            this.$navigate({
              page: 'order'
            })
            uni.hideToast();
          },
        });


      }catch(e){
        uni.hideToast();
      }
    }
  },
};
</script>

<style lang="less">
.confirm-order-wrap {
  display: flex;
  width: 100vw;
  min-height: 100vh;
  padding-bottom: calc(constant(safe-area-inset-bottom));
  padding-bottom: calc(env(safe-area-inset-bottom));
  flex-direction: column;
  align-items: center;
  background-color: #f5f5f5;
  .address {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 710rpx;
    border-radius: 20rpx;
    margin-top: 28rpx;
    background-color: #ffffff !important;
    background-size: 100% !important;
    &__section {
      flex: 1;
    }
    &__content {
      padding: 40rpx 36rpx;
    }
    &__user {
      display: flex;
      align-items: center;
      margin-bottom: 12rpx;
      &-name,
      &-mobile {
        font-size: 32rpx;
        font-weight: 500;
      }
      &-name {
        margin-right: 48rpx;
      }
    }
    &__info {
      max-width: 508rpx;
      line-height: 40rpx;
    }
    &__action {
      font-size: 44rpx;
      flex-shrink: 0;
      margin-right: 20rpx;
      color: #999999;
    }
  }

  .bill {
    width: 710rpx;
    border-radius: 20rpx;
    background: #fff;
    padding: 32rpx 32rpx 42rpx;
    margin: 20rpx 0 0;
    &__cell {
      display: flex;
      justify-content: space-between;
      min-height: 60rpx;
      margin-top: 30rpx;
      &:first-child {
        margin-top: 36rpx;
      }
      &-label,
      &-content {
        display: flex;
        align-items: center;
        font-size: 30rpx;
        color: #494949;
        min-height: 60rpx;
        .icon-arrow-right-1 {
          font-size: 24rpx;
          color: #ababab;
          margin-left: 10rpx;
        }
      }
      &-label {
        height: 60rpx;
      }
    }
    .item-card-wrap {
      position: relative;
      display: flex;
    }
    .pic {
      flex-shrink: 0;
      width: 180rpx;
      height: 180rpx;
      margin-right: 32rpx;
      border-radius: 20rpx;
      background-color: #808080;
    }
    .info {
      flex: 1;
      &__title {
        height: 80rpx;
        display: -webkit-box;
        overflow: hidden;
        text-overflow: ellipsis;
        word-wrap: break-word;
        white-space: normal !important;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }
      &__skuProperty {
        margin-top: 10rpx;
        margin-bottom: 16rpx;
        font-size: 26rpx;
        color: #ababab;
      }
      &__sale {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 28rpx;
        color: #333333;
        .stock {
          font-size: 26rpx;
          color: #ababab;
        }
      }
    }
  }
  .btn-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: fixed;
    bottom: 0;
    bottom: calc(constant(safe-area-inset-bottom));
    bottom: calc(env(safe-area-inset-bottom));
    left: 0;
    height: 136rpx;
    width: 100%;
    padding-left: 40rpx;
    padding-right: 20rpx;
    background-color: #ffffff;
    .total-price {
      font-size: 32rpx;
      font-weight: 500;
      .price {
        color: #ff3841;
      }
    }
    .pay-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 300rpx;
      height: 92rpx;
      font-size: 32rpx;
      font-weight: 500;
      background-color: #fedd00;
      &.disable {
        opacity: 0.6;
        background-color: #f5f5f5;
      }
    }
  }
  .agree{
    display: flex;
    align-items: center;
    margin-top: 40rpx;
    margin-bottom: -10rpx;
    .icon-circle{
      margin-right: 10rpx;
      font-size: 28rpx;
      color: #999999;
    }
    .on{
      color: #4caf50;
    }
  }
  .tip-box{
    width: 100%;
    .tip{
      padding-top: 20rpx;
      padding-left: 20rpx;
      font-size: 24rpx;
      color: #999999;
      text-align: center;
    }
  }
}
</style>
